<template>
	<view class="container">
		<view class="header-img">
			<image src="../static/images/indexheadertitle.png" mode="" class="bottom-img"></image>
			<span style="display: flex; align-items: center; justify-content: right; width: 70%;">长按＋号添加新产线</span>
		</view>
		<view class="blue-arc-rectangle">
			<view class="left-section">
				<view class="title">智能产线</view>
				<view class="device-count" style="">{{ filteredDevices.length }} / {{$store.state.maxDeviceNumber}} 台设备</view>
			</view>
			<view class="img-box"><image src="../static/images/women.png" class="img-women"></image></view>
			
			<view class="right-section">
				<button @click="openDeviceModal" @longpress="openModal" class="add-line-button">+</button>
				<!-- 	<view v-if="showModal" class="modal">
					<view class="modal-content">
						<span class="close-button" @click="closeModal">&times;</span>
						<view style="text-align: center;font-size: 25rpx;">添加产线
							<image src="../static/images/addsuccess.png" class="img-add-success"></image>
						</view>
						<form @submit.prevent="submitForm">
							<label for="line-name">产线名称:</label>
							<input type="text" id="line-name" v-model="lineNameToAdd" >
							<button type="submit">确认添加</button>
						</form>
					</view>
				</view> -->
				<view v-if="showModal" class="modal-overlay">
					<view class="modal-content">
						<view class="modal-header">
							<span class="modal-title">添加产线</span>
							<span class="close-button" @click="closeModal">&times;</span>
						</view>
						<view class="modal-body">

							<view class="form-group">
								<label>产线名称:</label>
								<input type="text" v-model="lineNameToAdd" required />
							</view>

							<view class="modal-footer">
								<button class="delete-button" @click="submitRoom(1)">确认添加</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="flex">
			<scroll-view scroll-x="true" style="white-space: nowrap;">
			<view class="room-all">
				<view v-for="(room, index) in roomlist" :key="index" @click="selectRoom(index)" 
				@longpress="showDeleteConfirmation(room.name, index)" @dblclick="openEditDialog(index)" class="room-item" :class="{'room-list': true, 'selected': selectedRoomIndex === index }">
						<view class="room-name">{{ room.name }}</view>	</view>
		
					</view>
					</scroll-view>
			</view>
			
		<!-- 	<view v-if="showRoomList" class="dropdown">
				<span @click="toggleRoomList" class="cancel-button">&times;</span>
				<view>注意：产线删除后会重置所有设备，请谨慎操作。</view> 
				<select v-model="roomIdToDelete" class="custom-dropdown">
					<option disabled value="">选择要删除的产线</option>
					<option v-for="(room, index) in roomlist" :key="index" :value="room.id">{{ room.name+room.id }}</option>
				</select>
				<button @click="deleteRoom()" class="delete-button">确认删除</button>
			</view> -->
		<view v-if="showAddDeviceModal" class="modal-overlay">
		    <view class="modal-content">
		     <view class="modal-header">
		       <span class="modal-title">添加设备</span>
		       <span class="close-button" @click="closeDeviceModal">&times;</span>
		     </view>
		      <view class="modal-body">
<!-- 		        <view class="form-group">
		          <label>设备名：</label>
		          <input style="font-size: 20rpx;" type="text" v-model="deviceName"/>
		        </view> -->
		        <view class="form-group">
		          <label>设备类型（点击类型进行选择）：</label>
							<picker class="picker-o" mode="selector" :range="deviceType" @change="deviceTypeChange">
							  <view class="picker-view">{{ selectedDeviceType }}</view>
							</picker>			   
		        </view>
		      </view>
		      <view class="modal-footer">

		        <button class="confirm-button" @click="confirmChanges">确认添加</button>
		      </view>
		    </view>
		  </view>
			   
			<!-- Delete Dialog s删除产线-->
			<view v-if="showDeleteDialog" class="delete-dialog">
				<view class="modal-header"><text class="del-class">确认删除 {{ roomToDelete }} 吗</text></view>
				<view class="modal-body">
					<view class="form-group">
					<label style="font-size: 20rpx; width: 100%; margin-bottom: 8rpx;">注意：只有产线内没有设备，才可以删除产线</label> 
					</view>
					</view>
			    <view class="dialog-buttons">
			      <button @click="confirmDelete" style="background-color:#8DC2FF; color: white; width: 175rpx;">确认</button>
			      <button @click="cancelDelete" style="background-color:#8DC2FF; color: white; width: 175rpx;">取消</button>
			    </view>
				</view>

		<view class="item-container">
			<navigator :url="getNavigateUrl(item)" class="item" v-for="(item, index) in filteredDevices" :key="index">
				<image :src="selectDeviceImg(item)" class="item-device-img" mode="aspectFit"></image>
				
					<view class="basic-flex">
<!-- 					<image :src="getDeviceImg(item)" class="item-device-img" mode="aspectFit"></image> -->
						<view class="ellipsis custom-name" style="" >
						{{ item.customName }}
						</view>
					</view>
					<view class="basic-flex">
	<!-- 					<image src="../static/images/open.png" class="item-icon" mode="aspectFit"></image> -->
						<view :style="getDeviceStatusStyle(item)">{{ item.status==1?"在线":"离线" }}</view>
					</view>
			</navigator>
		</view>

	</view>
</template>

<script>
	import { listRoom, delRoom, addRoom, updateRoom } from "@/api/system/room.js";
	import { listDevice, getNavigateUrlBase  } from "@/api/system/device.js";
	import { setCache } from "@/utils/cache.js";
	import msgUtils from "@/plugins/modal.js";
	
	export default {
		data() {
			return {
				navigateUrl:'',
				loading: false,
				showModal: false,
				showAddDeviceModal: false,
				showRoomList: false,
				// <!-- Delete Dialog s删除产线-->
					  selectedRoomIndex: null,
				      showDeleteDialog: false,
				      roomToDelete: '',
				      indexToDelete: null,
					  
					   // <!-- Edit Dialog 修改产线-->
					 showEditDialog: false,
					       editRoomNameInput: '',
					  
				form: {
				  id: null,
				  name: null,
				  sysUserName: null,
				  remark: null
				},
				lineNameToAdd: '',
				userName: '',
				queryParamsRoom: {
				  pageNum: 1,
				  pageSize: this.$store.state.maxDeviceNumber,
				  sysUserName: this.$store.state.user.name,
				},
				queryParamsDevice: {
				  pageNum: 1,
				  pageSize: this.$store.state.maxDeviceNumber,
				  productionId: null,
				},
				roomlist: [{
						id: 1,
						name: "产线1"
					},
					{
						id: 2,
						name: "产线2"
					},
					{
						id: 3,
						name: "产线3"
					}
				],
				devices: [],
				
				showModal: false,
				deviceName: '',
				
				deviceType: ['温度传感器', '小车状态传感器', '未开发设备'],
				deviceTypeNum: [1, 2, 3],
				selectedDeviceTypeIndex: 0,
				productionLines: [1, 2, 3],
				selectedProductionLineIndex: 0,
			};
		},
		computed: {
			filteredDevices() {
				if (this.selectedRoomIndex != null) {
					const selectedRoomId = this.roomlist[this.selectedRoomIndex].id;
					return this.devices.filter(device => device.productionId === selectedRoomId);
				} else {
					return this.devices;
				}
			},
			selectedDeviceType() {
				return this.deviceType[this.selectedDeviceTypeIndex];
			},
			selectedDeviceTypeVal() {
				return this.deviceTypeNum[this.selectedDeviceTypeIndex];
			}
		},
		onLoad() {
			this.getProductionList()
			this.$modal.closeLoading()
			this.$store.state.maxDeviceNumber = 10
			// this.showDeleteConfirmation('未初始化设备',0)
			this.userName = this.$store.state.user.name
		},
		onShow() {
			// this.getProductionDeviceList()
		},
		methods: {
			getProductionList() {
			  listRoom(this.queryParamsRoom).then(response => {
			    this.roomlist = response.rows;
				setCache("production", this.roomlist);
				console.log(response.rows)
				console.log(this.roomlist)
				msgUtils.closeLoading()
			  });
			},
			getDeviceList() {
			  listDevice(this.queryParamsDevice).then(response => {
			    this.devices = response.rows;
				setCache("device", this.devices);
				console.log(response.rows)
				console.log(this.devices)
				msgUtils.closeLoading()
			  });
				// this.$delay(2000)
			},
			getProductionDeviceList() {
			  // msgUtils.loading("加载产线设备列表中...")
			  console.log(this.queryParamsDevice)
				if(this.queryParamsDevice.productionId!=null){
					msgUtils.loading("加载产线设备列表中...")
				}
			  listDevice(this.queryParamsDevice).then(response => {
			    this.devices = response.rows;
				console.log(response.rows)
				console.log(this.devices)
			    msgUtils.closeLoading()
			  });
			},
			
			selectDeviceImg(item){
			return item.type==1?"../static/images/deviceicon22.png":item.type==2?"../static/images/deviceicon33.webp":"../static/images/deviceicon.png";
			},
			
			
			
			getNavigateUrl(deviceType){
				return getNavigateUrlBase(deviceType)
			},
			getDeviceStatusStyle(item){
				return item.status==1?"font-size: 25rpx; color: green":"font-size: 25rpx; color: darkgray";
			},
			getDeviceImg(item){
				return item.type==1?"../static/images/温度计(英文命名)img.png":"../static/images/小车(英文命名)img.png";
			},
			openModal() {
				this.showModal = true;
			},
			closeModal() {
				this.showModal = false;
			},
			openDeviceModal() {
				this.showAddDeviceModal = true;
			},
			closeDeviceModal() {
				this.showAddDeviceModal = false;
			},
			// loadingHandler(msg){
			// 	if(this/./loading == true){
			// 		msgUtils.loading(msg)
			// 		setInterval(()=>{
			// 			if(this/./loading == false){
			// 				msgUt/ils.clo/seLoading()
			// 			}
			// 		},500)
			// 	} else{
			// 		msg/Utils.closeLo/ading()
			// 	}
			// },
			
			deleteRoom(id, name) {
				console.log("xxx"+id)
				msgUtils.loading("正在删除产线...")
				delRoom(id).then(res => {
					if(this.selectedRoomIndex!=null && this.selectedRoomIndex >= this.indexToDelete){
						this.selectedRoomIndex--
						console.log(123)
						this.selectRoom(this.selectedRoomIndex)
					}
					this.submitRoomSucc("已删除产线："+name)
					
					this.showDeleteDialog = false;
				},rej => {
					this.submitRoomError("删除产线："+name+"失败，请清空产线内设备再试")
					this.showDeleteDialog = false;
				});
			},
			
			submitRoomError(msg) {
				this.getProductionList();
				msgUtils.msgError(msg)
				msgUtils.closeLoading()
			},
			submitRoomSucc(msg) {
				this.getProductionList();
				msgUtils.msgSuccess(msg)
				msgUtils.closeLoading()
			},
			submitRoom(operation) {
				var flag = false;
				this.closeModal();
				// 添加产线的逻辑
				msgUtils.loading("提交中...")
				this.form.name = this.lineNameToAdd;
				if(operation == 1){ //添加
					this.form.sysUserName = this.userName;
					addRoom(this.form).then(res =>{
						flag = true;
						this.submitRoomSucc("已添加：" + this.lineNameToAdd);
						this.form = {};
						this.lineNameToAdd = "";
					});					
				} else if(operation == 2){ //修改
					updateRoom(this.form).then(res =>{
						flag = true;
						this.submitRoomSucc("已修改：" + this.lineNameToAdd);
						this.form = {};
						this.lineNameToAdd = "";
					});	
				}
			},
			// <!-- Delete Dialog s删除产线-->
			selectRoom(index) {
			    this.selectedRoomIndex = index;
				  this.queryParamsDevice.productionId = this.roomlist[index].id;
				  this.getProductionDeviceList()
					this.getProductionList()
			      // Handle selection logic
			    },
			    showDeleteConfirmation(roomName, index) {
			      // Show delete confirmation dialog
				  if(index == 0){
					  msgUtils.msgError('该产线是默认产线，不可删除！')
					  return
				  }
			      this.roomToDelete = roomName;
			      this.indexToDelete = index;
			      this.showDeleteDialog = true;
			    },
			    confirmDelete() {
			      // Implement delete logic
				 //  if(this.roomlist[this.indexToDelete].id == undefined){
					// this.showDeleteDialog = false;
				 //  }
				  
				  const roomId = this.roomlist[this.indexToDelete].id;
				  const roomName = this.roomlist[this.indexToDelete].name;
				  
			      this.deleteRoom(roomId, roomName)
			      
			    },
			    cancelDelete() {
			      // Cancel delete operation
			      this.showDeleteDialog = false;
			    },
				
				 // <!-- Edit Dialog 修改产线 不能用 修改中！！！！-->
			 openEditDialog(index) {
			      this.editRoomNameInput = this.roomlist[index].name; // Load current room name
			      this.showEditDialog = true;
			    },
			    closeEditDialog() {
			      this.showEditDialog = false;
			    },
			    saveEditedRoomName() {
			      if (this.editRoomNameInput.trim() === '') {
			        // Handle empty input case if necessary
			        return;
			      }
			      // Update the room name in the roomlist array
			      this.roomlist[this.selectedRoomIndex].name = this.editRoomNameInput;
			      // Close the edit dialog
			      this.closeEditDialog();
			    },
				    // saveEditedRoomName() {
				    //   if (this.editRoomNameInput.trim() !== '') {
				    //     this.roomlist[this.selectedRoomIndex].name = this.editRoomNameInput.trim();
				    //     this.closeEditDialog();
				    //   } else {
				    //     alert('请输入有效的产线名称');
				    //   }
				    // }
			deviceTypeChange(e) {
					this.selectedDeviceTypeIndex = e.detail.value;
					console.log(this.selectedDeviceTypeIndex)
				},
			confirmChanges() {
				// 确认添加的逻辑
				// uni.showLoading({
				// 	title:'正在配网...'
				// })
				uni.navigateTo({
					url:`/pages/main?type=${this.selectedDeviceTypeVal}`
				})
				this.closeModal();
			}
		},
	}
</script>

<style>
	@import url("@/css/common.css");
	
	::v-deep uni-scroll-view {
		width: 100% !important;
	}
	
	.custom-name{
		width: 200rpx;
		font-size: 35rpx;
		margin-top: 5rpx;
		margin-bottom: 2rpx;
		text-align: center;
		color:#2F2E41;
	}
	
	.header-img{
		display: flex;
		 justify-content:left; /* 水平居中 */
		 /* margin-bottom: 2%; */
		 /* margin-top: 7%; */
	}
	.bottom-img{
		width: 200rpx;
		height: 90rpx;
		margin-left: 2%;
	}
	
	.img-box{
		display: flex;
		 /* justify-content: center; /* 水平居中 */ 
		 margin-top:2%;
	}
	.img-women{
		
		width: 300rpx;
		height: 285rpx;
	}
	
	.delete-dialog {
	  position: fixed;
	  top: 50%;
	  left: 50%;
	  transform: translate(-50%, -50%);
	  background-color: white;
	  padding: 20rpx;
	  border-radius: 10rpx;
	  border: 1rpx solid #ccc;
	  box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
	  width: 80%;
	  height: 290rpx;
	  align-items: center;
	  justify-content: center; 
	  z-index: 3;
	  
	}
	.del-class{
	/* 	display: flex;
		font-size: 22rpx;
		margin-bottom: 10rpx; */
		font-size: 25rpx;
		/* font-weight: bold; */
		color: #8DC2FF;
		border: 2rpx solid #ffffff;
		margin-bottom: 15rpx;
	}
	
	.dialog-buttons {
	  display: flex;
	  justify-content: flex-end;
	  margin-top: 35          rpx;
	  font-size: 16rpx;

	  color: #8DC2FF;
	}

	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 3;

	}

	.modal-content {
		background: white;
		border-radius: 10rpx;
		width: 80%;
		padding: 20rpx;
		z-index: 3;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.modal-title {
	font-size: 26rpx;
	font-weight: bold;
	color: #8DC2FF;
	border: 2rpx solid #ffffff;
	}

	.close-button {
		font-size: 24rpx;
		cursor: pointer;
	}

	.modal-body .form-group {
		margin-bottom: 38rpx;
	}

	.modal-body label {
		display: block;
		margin-bottom: 5rpx;
	}

	.modal-body input {
		width: 100%;
		height: 100rpx;
		padding: 10rpx;
		border-radius: 5rpx;
		border: 1rpx solid #ccc;
	}

	.modal-footer {
		display: flex;
		justify-content: space-between;
	}



	.dropdown {
		position: absolute;
		background-color: #f9f9f9;
		box-shadow: 0rpx 8rpx 16rpx 0rpx rgba(0, 0, 0, 0.2);
		padding: 22rpx 76rpx;
		z-index: 1;
		border: 1rpx solid #ADD8E6;
		/* 浅蓝色边框 */
		border-radius: 10rpx;
	}

	.custom-dropdown {
		width: 200rpx;
		padding: 10rpx;
		font-size: 16rpx;
		border: 1rpx solid #617a81;
		/* 浅蓝色边框 */
		border-radius: 5rpx;
		background-color: #F9F9F9;
		appearance: none;
		/* 移除默认箭头 */
		/* background-image: url('../static/images/arrow-down.png'); /* 自定义下拉箭头 */
		background-repeat: no-repeat;
		background-position: right 10rpx center;
		background-size: 20rpx;
	}

	.cancel-button {
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		font-size: 18rpx;
		cursor: pointer;
	}

	.delete-button {
		background-color: #8DC2FF;
		/* 浅蓝色背景 */
		color: white;
		padding: 5rpx 10rpx;
		border: none;
		border-radius: 30rpx;
		/* 圆角边框 */
		cursor: pointer;
		font-size: 19rpx;
		width: 300rpx;
		margin-top: 20rpx;
	}

	.flex {
		width: 100%;
		display: flex;
	}

	.item-container {
		z-index: 0;
		position: relative;
		padding-left: 20rpx;
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		/* 设置为相对定位，以便子元素可以使用绝对定位 */
		justify-content: left;
	}

	.item {
		width: 44vw;
		padding: 15rpx;
		align-items: center;
		margin-bottom: 10rpx;
		border-radius: 10rpx;
		/* 圆角边框 */
		background-color: #ffffff;
		padding: 20rpx;
		/* border: 1rpx solid white; */
		/* 设置外边框为黑色 */
		 box-shadow: 0 9rpx 15rpx rgba(63, 132, 211, 0.2); /* 阴影效果 */ 
		/* gap: 90rpx; */
		display: flex;
		flex-direction: column;
		/* 容器内的子元素将垂直排列 */
	}

	.item-device-img {
		width: 135rpx;
		height: 90rpx;
	}

	.item-icon {
		width: 90rpx;
		height: 90rpx;
		padding: 20rpx;
		background: #efefef;
		border-radius: 50%
	}

	.basic-flex {
		display: flex;
		align-items: right;
		justify-content: center;
		column-gap: 50rpx;
	}
	
	.course-name {
	   position: absolute; 
	    top: 13rpx; /* 根据 padding 调整 */  
	    left: 28rpx; /* 根据 padding 调整 */
		font-size: 26rpx;
		/* font-weight: bold;/*加粗*、 */
	}

	.container {
		padding: 15rpx;
		background: #efefef;
	}

	.room-all {
		margin: 20rpx 20rpx -40rpx 20rpx;
		display: flex;
		width:750rpx;
		height: 95rpx;
		/* justify-content: space-between; */
		position: relative;
		/* 确保子元素相对于这个容器进行定位 */
		overflow: auto;
	}

	.room-list {
		/* 	width: 10vw; */
		text-align: center;
		margin-right: 45rpx;
		/* 间隔 */
	}

	.room-name {
		color: gray;
		
		font-size: 40rpx;
		padding-bottom: 50rpx;
		/* font-weight: bold; */
	}

	.room-list.selected .room-name {
		color:#2F2E41;
		/* font-weight: bold; */
	}

	.fixed-image {


		width: 73rpx;
		height: 73rpx;


	}
	.picker-o{
		flex: 2;
		border: 1rpx solid #ccc;
		height: 70rpx;
		padding: 10rpx;
		border-radius: 10rpx;
		margin-left: 5rpx;
		margin-right: 30rpx;
		font-size: 30rpx;
		color: black;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.picker-view{
		
	}
	.header-container {
		width: 100%;
		/* display: flex;  */
		justify-content: center;
		align-items: center;
		height: 100rpx;
		/* 根据需要调整 */
		background-color: #ffffff;
		/* 假设头部背景色为白色 */
	}

	.blue-arc-rectangle {
		width: 100%;
		/* 根据需要调整 */
		height: 350rpx;
		/* 根据需要调整 */
		display: flex;
		/* margin: auto; */
		justify-content: space-between;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		/* 创建一个蓝色圆弧效果 */
		background: #8DC2FF;
		background-origin: border-box;
		border: 2rpx solid #ffffff;
		/* 白色边框 */
		padding: 10rpx;
		/* 根据需要调整内边距 */
		box-sizing: border-box;
		/* margin-top: 5rpx; */
		margin-bottom: 10rpx;
		margin-top: 2rpx;

	}

	.left-section {
		flex-direction: column;
		justify-content: center;
	}

	.title {
		font-size: 50rpx;
		font-weight: 500;
		/* 根据需要调整 */
		color: #2F2E41;
		margin-top: 15rpx;
		margin-bottom: 8rpx;
	}

	.device-count {
		font-size: 50rpx;
		/* 根据需要调整 */
		color: #ffffff;
		/* 灰色字体 */
		margin-top: 25rpx;
		margin-left: 5px;
	}

	.right-section {
		justify-content: center;
		align-items: center;
	}

	.add-line-button {
		margin: 10rpx 10rpx 0 0;
		width: 100rpx;
		/* 圆的直径 */
		height: 100rpx;
		border-radius: 50%;
		/* 设置为50%使其变成圆形 */
		background-color: white;
		/* 背景色为白色 */
		position: relative;
		/* 用于定位内部的加号按钮 */
		display: flex;
		/* 使用Flexbox来居中加号按钮 */
		justify-content: center;
		align-items: center;
		color: #8DC2FF;
		/* 蓝色字体 */
		font-size: 66rpx;
		/* 根据需要调整字体大小 */
	}

	.modal {
		display: block;
		/* 修改为block来显示 */
		position: fixed;
		z-index: 1;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
		background-color: rgba(0, 0, 0, 0.4);
		/* Black w/ opacity */
	}

	/* Modal Content Box */


	/* Close Button */

	.modal-content label {
		display: block;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		font-size: 20rpx;
	}

	.modal-content input[type="text"] {
		width: calc(100% - 22rpx);
		/* 全宽度减去 padding 和边框 */
		padding: 10rpx;
		margin-bottom: 60rpx;
		border: 1rpx solid #85b4dd;
		border-radius: 5rpx;
		/* 圆角边框 */
		box-sizing: border-box;
		font-size: 30rpx;
		/* 包含 padding 和边框在内的盒模型 */
	}

	/* Submit Button */
	.modal-content button[type="submit"] {
		background-color: #1296db;
		/* 浅蓝色背景 */
		color: white;
		padding: 5rpx 10rpx;
		border: none;
		border-radius: 5rpx;
		/* 圆角边框 */
		cursor: pointer;
		font-size: 16rpx;
		width: 260rpx;
		margin-top: 20rpx;
	}

	.modal-content button[type="submit"]:hover {
		background-color: #87ceeb;
		/* 提供一个更深的蓝色用于悬停状态 */
	}
</style>